<template>
  <!--角色权限配置页-->
  <el-card class="app-container">
    <c-u-r-d-table :option="option"/>
    <el-dialog title="权限配置" :visible.sync="grade.box" width="40%" append-to-body>
      <div class="permission" v-loading="loadingGrade">
        <div class="permission__role">
          角色 ：{{ currentRole.title }}
        </div>
        <div style="padding-bottom: 10px;">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
          </el-checkbox>
        </div>
        <!--        <el-checkbox-group v-model="formData.permissionIdList" @change="handleCheckedPermissionsChange">-->
        <table>
          <thead>
          <tr>
            <th>模块</th>
            <th>权限</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="item in permissions" :key="item.title">
            <td>
              <el-checkbox
                v-model="item.checked"
                @change="handleCheckedModuleChanged($event,item)"
                v-if="item.permissions.length > 1">
                {{ item.title }}
              </el-checkbox>
              <div v-else>
                {{ item.title }}
              </div>
            </td>
            <td>
              <div class="rolePermission">
                <el-checkbox
                  v-for="p in item.permissions"
                  v-model="p.checked"
                  :key="p.permissionId"
                  @change="handleCheckedPermissionChanged($event,item)"
                >
                  {{ p.permissionTitle }}
                </el-checkbox>
              </div>

            </td>
          </tr>
          </tbody>
        </table>
        <!--        </el-checkbox-group>-->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="isUpdatingGrade" size="mini" type="primary" @click="handleGradeUpdate">保存权限</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>

import ColumnType from '@/framework/constant/ColumnType'
import CURDTable from '@/framework/components/table/CURDTable'
import {permissionApi} from '@/feature/mgr/infra/api/permissionApi'
import {roleApi} from '@/feature/mgr/infra/api/roleApi'

export default {
  components: {CURDTable},
  data() {
    return {
      filterText: '',
      isUpdatingGrade: false,
      grade: {
        box: false,
        check: []
      },
      isIndeterminate: false,
      checkAll: false,
      formData: {
        permissionIdList: []
      },
      currentRole: {},
      permissions: [],
      expandAll: true,
      loadingGrade: false,
      option: {
        dialogWidth: '500px',
        requestApi: roleApi,
        showSelection: false,
        columns: [
          {
            label: '角色名称',
            searchable: true,
            width: 300,
            span: 24,
            required: true,
            prop: 'title'
          },
          {
            label: '创建时间',
            type: ColumnType.DATETIME,
            hiddenInForm: true,
            prop: 'gmtCreate'
          },
          {
            label: '修改时间',
            type: ColumnType.DATETIME,
            hiddenInForm: true,
            prop: 'gmtModified'
          }
        ]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.nodeTree.filter(val)
    }
  },
  computed: {

    // allPermissionIdList() {
    //   const moduleIdList = this.groupPermissions.map(el => 'm' + el.moduleId)
    //   return this.permissions.map(el => el.permissionId).concat(moduleIdList)
    // }
  },
  // computed: {
  //   leafNodes() {
  //     return TreeUtil.getLeafNodes(this.permissions)
  //   }
  // },
  methods: {
    calcGroup() {
      const map = this.permissions.reduce((r, a) => {
        r[a.moduleTitle] = r[a.moduleTitle] || []
        a.checked = false
        r[a.moduleTitle].push(a)
        return r
      }, {})
      this.groupPermissions = Object.keys(map).map(key => ({
        title: key,
        checked: false,
        permissions: map[key],
        moduleId: map[key][0].moduleId
      })).sort((a, b) => a.moduleId > b.moduleId ? 1 : (a.moduleId < b.moduleId ? -1 : 0))
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleDisExpandAll() {
      this.expandAll = false
      this.buildData()
    },
    handleCheckedPermissionChanged(checked, item) {
      if (!checked) {
        item.checked = false
      } else {
        item.checked = !item.permissions.some(el => !el.checked)
      }
      this.calcCheckAll()
    },
    calcCheckAll() {
      this.checkAll = !this.permissions.some(el => el.permissions.some(i => !i.checked))
    },
    handleCheckedModuleChanged(checked, item) {
      item.permissions.forEach(i => {
        i.checked = checked
      })
      this.calcCheckAll()
    },
    handleCheckAllChange(val) {
      this.permissions.forEach(item => {
        item.checked = val
        item.permissions.forEach(v => {
          v.checked = val
        })
      })
    },
    handlePower({arg: row}) {
      this.currentRole = row
      this.grade.box = true
      this.loadingGrade = true
      this.permissions = []
      permissionApi.allPermissions(row.id).then(data => {
        this.permissions = data
        this.calcCheckAll()
      }).finally(() => {
        this.loadingGrade = false
      })
    },
    handleGradeUpdate() {
      this.isUpdatingGrade = true
      roleApi.savePermissions({
        roleId: this.currentRole.id, permissionIdList: this.permissions.reduce((r, a) => {
          const permissionIdList = a.permissions.filter(el => el.checked).map(el => el.permissionId)
          if (permissionIdList && permissionIdList.length) {
            r.push(...permissionIdList)
          }
          return r
        }, [])
      })
        .then(() => {
          this.isUpdatingGrade = false
          this.grade.box = false
          this.$success()
        })
        .catch(() => {
          this.isUpdatingGrade = false
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.permission {
  min-height: 300px;
  &__role {
    padding-bottom: 30px;
  }

  table {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;

    th {
      background: #F4F4F4;
      text-align: left;
    }

    td, th {
      border: 1px solid #eee;
      padding: 15px 20px;
    }

    th:first-child {
      width: 200px;
    }
  }
}

::v-deep .el-checkbox-group {
  font-size: 14px;
}
.rolePermission{
  line-height: 2.4;
}
</style>

